package com.wang.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.project.model.dto.InterfacePay.InterfacePaymentRequest;
import com.wang.project.service.UserInterfaceInfoService;
import com.wang.project.common.ErrorCode;
import com.wang.project.constant.UserConstant;
import com.wang.project.exception.BusinessException;
import com.wang.project.mapper.UserInterfaceInfoMapper;
import com.wang.project.model.dto.userinterfaceinfo.UserInterfaceInfoGetRequest;
import com.wang.project.model.entity.InterfaceInfo;
import com.wang.project.model.entity.User;
import com.wang.project.model.entity.UserInterfaceInfo;
import com.wang.project.service.InterfaceInfoService;
import com.wang.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 胡歌的腿毛
 * @description 针对表【user_interface_info(用户调用接口关系表)】的数据库操作Service实现
 * @createDate 2023-05-08 20:49:55
 */
@Service
@Slf4j
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo> implements UserInterfaceInfoService {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        if (userInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 创建时，所有参数必须非空
        if (add) {
            if (userInterfaceInfo.getInterfaceInfoId() <= 0 || userInterfaceInfo.getUserId() <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口或用户id不存在");
            }
        }
        if (userInterfaceInfo.getLeftNum() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余调用次数小于0");
        }
    }


    /**
     * 调用接口统计
     *
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interfaceInfoId", interfaceInfoId);
        updateWrapper.eq("userId", userId);
        // todo 当用户突然调用很多次接口，在高并发的情况，这样写就会出现问题，可以使用锁和事物去解决这个并发问题
        //updateWrapper.gt("leftNum", 0);
        updateWrapper.setSql("leftNum = leftNum -1 , totalNum = totalNum  +1");

        return this.update(updateWrapper);
    }

    /**
     * 获取当前用户的这个接口还有多少次调用机会
     *
     * @param interfaceInfoId
     * @param userId
     * @return
     */
    @Override
    public Integer getInvokeUserCount(long interfaceInfoId, long userId) {
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        queryWrapper.eq("interfaceInfoId", interfaceInfoId);
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoMapper.selectOne(queryWrapper);
        Integer leftNum = userInterfaceInfo.getLeftNum();
        return leftNum;
    }

    /**
     * 用户获取接口调用权限  免费获取
     * todo 后续可能扩展为需要一定条件才能获取接口的权限
     *
     * @param userInterfaceInfoGetRequest
     * @param request
     * @return
     */
    @Override
    public Boolean getInterfaceNum(UserInterfaceInfoGetRequest userInterfaceInfoGetRequest, HttpServletRequest request) {
        if (userInterfaceInfoGetRequest == null) {
            log.info("UserInterfaceInfoController getInterfaceNum 参数无法为空");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
        if (userInterfaceInfoGetRequest.getInterfaceInfoId() < 0) {
            log.info("UserInterfaceInfoController getInterfaceNum 用户接口id或者用户id 参数错误");
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        BeanUtils.copyProperties(userInterfaceInfoGetRequest, userInterfaceInfo);
        User loginUser = userService.getLoginUser(request);
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(userInterfaceInfoGetRequest.getInterfaceInfoId());
        if (loginUser == null || interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        userInterfaceInfo.setTotalNum(UserConstant.INTERFACEDEFAULTNUM);
        userInterfaceInfo.setLeftNum(UserConstant.INTERFACEDEFAULTNUM);
        userInterfaceInfo.setUserId(loginUser.getId());
        userInterfaceInfo.setStatus(interfaceInfo.getStatus());
        Boolean result = this.save(userInterfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return result;
    }
}




